﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace webui.Filters
{
    public class AppErrorAttribute:HandleErrorAttribute
    {

        public override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);
            if (!filterContext.ExceptionHandled)
            {
                string ControllerName = string.Format("{0}Controller", filterContext.RouteData.Values["controller"] as string);
                string ActionName = filterContext.RouteData.Values["action"] as string;


                NameValueCollection gets = filterContext.HttpContext.Request.QueryString;
                List<string> listget = new List<string>();
                foreach (string key in gets)
                {
                    listget.Add(string.Format("{0}={1}", key, gets[key]));
                }

                NameValueCollection posts = filterContext.HttpContext.Request.Form;

                List<string> listpost = new List<string>();
                if (filterContext.HttpContext.Request.Files.Count <= 0)
                {
                    foreach (string key in posts)
                    {
                        listpost.Add(string.Format("{0}={1}", key, posts[key]));
                    }
                }

                string ErrorMsg = string.Format("在执行 controller[{0}] 的 action[{1}] 时产生异常。get参数：{2},post参数：{3}", ControllerName, ActionName, string.Join("&", listget.ToArray()), string.Join("&", listpost.ToArray()));
                ErrorMsg += "     \r\n异常信息：" + filterContext.Exception.ToString();
                //  Logger.Default.Error(ErrorMsg, filterContext.Exception);//用Nlog记录日志
                try
                {
                    Logger.Default.Error(ErrorMsg);//用Nlog记录日志
                }
                catch(Exception ce)
                {
                    string s1 = filterContext.Exception.Message;
                    s1 += filterContext.Exception.StackTrace;
                    Tools.CommonHellper.WriteLog(s1+"   222错误222 "+ ce.Message);
                }

              

            }
        }

    }
}